
import { ref } from "vue"
import type { questionType } from "./type"
import { getCourseInfoApi, getCourseDirectoryApi } from "#/api/manage/course"
import { LISTED_STATUS } from '#/types/const'

// 题目选项类型定义
interface OptionItem {
  value: string
  label: string
}

let question = ref<questionType>()

const useQuestionItem = () => {
  return question
}

const useClearQuestionItem = (): void => {
  question.value = {}
}



/**
 * 课程和章节管理的 hooks
 * @description 提供课程和章节数据的获取、管理和状态控制功能
 * @returns 返回课程章节相关的响应式数据和方法
 */
const useCourseChapter = () => {
  const courseOptions = ref<OptionItem[]>([])
  const chapterOptions = ref<OptionItem[]>([])
  const courseLoading = ref(false)
  const chapterLoading = ref(false)

  /**
   * 获取课程列表
   * @description 获取所有已发布状态的课程信息
   */
  const getCourseInfo = async (): Promise<void> => {
    if (courseLoading.value) return
    
    courseLoading.value = true
    try {
      const res: any = await getCourseInfoApi({
        curPage: 1,
        pageSize: 10000,
        // status: LISTED_STATUS
      })
      
      if (res?.data && Array.isArray(res.data)) {
        courseOptions.value = res.data.map((item: any) => ({
          value: item.id,
          label: item.name
        }))
      } else {
        courseOptions.value = []
      }
    } catch (error) {
      console.error('获取课程信息失败:', error)
      courseOptions.value = []
    } finally {
      courseLoading.value = false
    }
  }

  /**
   * 根据课程ID获取章节列表
   * @param courseId 课程ID
   * @description 根据指定的课程ID获取该课程下的所有章节信息
   */
  const getChapterInfo = async (courseId: string): Promise<void> => {
    if (!courseId || chapterLoading.value) return
    
    chapterLoading.value = true
    chapterOptions.value = []
    
    try {
      const res: any = await getCourseDirectoryApi(courseId)
      
      if (res && Array.isArray(res)) {
        chapterOptions.value = res.map((item: any) => ({
          value: item.id,
          label: item.name
        }))
      } else {
        chapterOptions.value = []
      }
    } catch (error) {
      console.error('获取章节信息失败:', error)
      chapterOptions.value = []
    } finally {
      chapterLoading.value = false
    }
  }

  /**
   * 处理课程变化
   * @param courseId 选中的课程ID
   * @description 当课程选择发生变化时，清空章节选项并重新获取章节列表
   */
  const handleCourseChange = (courseId: string): void => {
    chapterOptions.value = []
    if (courseId) {
      getChapterInfo(courseId)
    }
  }

  /**
   * 清空课程和章节数据
   * @description 清空所有课程和章节的选项数据，通常在组件销毁或重置时调用
   */
  const clearCourseChapterData = (): void => {
    courseOptions.value = []
    chapterOptions.value = []
  }

  return {
    courseOptions,
    chapterOptions,
    courseLoading,
    chapterLoading,
    getCourseInfo,
    getChapterInfo,
    handleCourseChange,
    clearCourseChapterData
  }
}

export {
  useQuestionItem,
  useClearQuestionItem,
  useCourseChapter
}
